package com.wanshi.controller.sql;


import com.alibaba.fastjson.JSON;
import com.wanshi.po.Record;
import com.wanshi.po.Result;
import com.wanshi.po.Timu;
import com.wanshi.service.RecordService;
import com.wanshi.service.TiService;
import com.wanshi.utils.JDBCUtil;
import com.wanshi.utils.RequestUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sql")
public class SqlController {

    @Autowired
    private RecordService recordService;

    @Autowired
    private TiService tiService;

    @PostMapping("/panduan")
    @ResponseBody
    public Result panduan(HttpSession session, String id,
                          String content){

        Record record = RequestUtils.getRecord(session, Integer.parseInt(id), content);

        if(content == null || content.equals("") || content.toLowerCase().contains("insert")
                || content.toLowerCase().contains("delete")|| content.toLowerCase().contains("update")){
            return RequestUtils.getResult(recordService, record, false);
        }

        QueryRunner runner= new QueryRunner(JDBCUtil.getSource());
        List<Map<String, Object>> list = null;
        boolean flag = false;
        try {
            //根据id获取正确答案
            //tiService
            Timu timu = tiService.findById(id);
            //获取正确记录
            list = runner.query(timu.getAnswer(), new MapListHandler());
            String s1 = JSON.toJSONString(list);

            //获取学生提交sql的查询记录
            list = runner.query(content, new MapListHandler());
            String s2 = JSON.toJSONString(list);

            flag = s1.equalsIgnoreCase(s2);
        } catch (Exception e) {
        }finally {
            return RequestUtils.getResult(recordService, record, flag);
        }
    }

}
